class Backend::AdminUsersController < Backend::BaseController
  before_action :set_admin_user, only: [:show, :edit, :update, :destroy, :switch]


  def index
    @search = AdminUser.all.ransack(params[:q])
    scope = @search.result
    @admin_users = scope.sorted.page(params[:page])
  end


  def show
  end

  def new
    @admin_user = AdminUser.new
  end

  def edit
  end

  def create
    @admin_user = AdminUser.new(admin_user_params)

    if @admin_user.save
      redirect_to referer_or(backend_admin_users_path), notice: '新增成功'
    else
      flash[:alert] = "新增失败"
      render :new
    end
  end

  def update
    if @admin_user == current_admin && admin_user_params[:state] == 0
      flash.now[:alert] = '不能禁用当前管理员'
      render :edit and return
    end
    if @admin_user.update(admin_user_params)
      redirect_to referer_or(backend_admin_users_path), notice: '修改成功'
    else
      flash[:alert] = "修改失败"
      render :edit
    end
  end

  def destroy
    if @admin_user.destroy
      redirect_to referer_or(backend_admin_users_path), notice: '删除成功'
    else
      redirect_to referer_or(backend_admin_users_path), alert: "删除失败"
    end
  end

  def switch
    @admin_user.active? ? @admin_user.forbidden! : @admin_user.active!
    redirect_to backend_admin_users_path, notice: @admin_user.active? ? "管理员已锁定" : "管理员已启用"
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_admin_user
    @admin_user = AdminUser.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def admin_user_params
    params.require(:admin_user).permit!
  end
end
